package org.sang.utils;

import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

public class RSAUtil {

    public static String encrypt(String data, String publicKey) throws Exception {
        // 使用Base64 编码的公钥解析为二进制
        byte[] publicKeyByte = Base64.getDecoder().decode(publicKey);
        // 得到公钥
        PublicKey pubKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(publicKeyByte));
        // 加密数据
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
        // 得到加密后的数据
        return Base64.getEncoder().encodeToString(cipher.doFinal(data.getBytes()));
    }

    public static String decrypt(String data, String privateKey) throws Exception{
        // 将 Base64 编码的私钥解析为二进制
        byte[] privateKeyByte = Base64.getDecoder().decode(privateKey);
        // 使用 Base64 解析后得到的加密数据
        byte[] dataByte = Base64.getDecoder().decode(data.getBytes());
        // 获取私钥
        PrivateKey priKey = KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(privateKeyByte));
        // RSA 解密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, priKey);
        // 得到解密后的数据
        return new String(cipher.doFinal(dataByte));
    }
}
